package com.itheima.activiti.listener;

import com.itheima.activiti.constant.ListenerConstant;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.EventListener;

//全局监听器
@Slf4j
@Component
public class GlobalEventListener implements ActivitiEventListener {
@Lazy
@Autowired
private TaskService taskService;
private void entityDeleted(ActivitiEvent event){

}
    @Override
    public void onEvent(ActivitiEvent activitiEvent) {
        switch (activitiEvent.getType()){
//            删除已存在的实体时触发
            case ENTITY_DELETED:
                entityDeleted(activitiEvent);
                break;
//                暂停已存在的实体时触发
            case ENTITY_SUSPENDED:
                entitySuspended(activitiEvent);
                break;
//                激活已存在的实体时触发
            case ENTITY_ACTIVATED:
                entityActivated(activitiEvent);
                break;
            case TASK_CREATED:
//                任务创建时
                taskCreate(activitiEvent);
                break;
//        任务完成时
            case TASK_COMPLETED:
                taskCompleted(activitiEvent);
                break;
//                流程结束时
            case PROCESS_CANCELLED:
                processCancelled(activitiEvent);
                break;
        }

    }

    private void processCancelled(ActivitiEvent activitiEvent) {
    }
//任务结束后，将审批结果添加到流程实例的备注字段
    private void taskCompleted(ActivitiEvent activitiEvent) {
        ActivitiEntityEventImpl activitiEntityEventImpl= (ActivitiEntityEventImpl) activitiEvent;
        TaskEntity taskEntity= (TaskEntity) activitiEntityEventImpl.getEntity();
        if (taskEntity.getVariable(ListenerConstant.OPERATE)!=null){
            String age= (String) taskEntity.getVariable(ListenerConstant.OPERATE);
            taskService.addComment(taskEntity.getId(),taskEntity.getProcessInstanceId(),ListenerConstant.OPERATE,age);
        }
}

    private void taskCreate(ActivitiEvent activitiEvent) {
    }

    private void entityActivated(ActivitiEvent activitiEvent) {
    }

    private void entitySuspended(ActivitiEvent activitiEvent) {
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}
